package org.example.rpc.framework.proxy;





import org.example.rpc.framework.RpcRequest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Desc: 代理类执行的逻辑
 */
public class RemoteInvocationHandler implements InvocationHandler {

    private String host;
    private int port;
    private Class clazz;

    public RemoteInvocationHandler(String host,int port,Class clazz){
        this.host = host;
        this.port = port;
        this.clazz = clazz;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest rpcRequest = new RpcRequest();

        rpcRequest.setClassName(clazz.getName());
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setTypes(method.getParameterTypes());
        rpcRequest.setParams(args);

        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;

        try {
            Socket socket = new Socket(host,port);
            // 发送消息
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(rpcRequest);
            objectOutputStream.flush();

            // 接受结果
            objectInputStream = new ObjectInputStream(socket.getInputStream());
            Object readObject = objectInputStream.readObject();
            return readObject;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (objectInputStream !=null){
                    objectInputStream.close();
                }
                if (objectOutputStream!=null){
                    objectOutputStream.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return null;
    }
}

